<template>
  <div>
    <div v-if="noData" class="no-data-show">
      <no-data size="200px"></no-data>
    </div>
    <div v-else>
      <!-- form 1 -->
      <el-form :model="form" label-width="70px" class="edit-form">
        <el-form-item label="接口描述">
          <el-input v-model="form.data.description" class="desc" :readonly="!currentIntf.isLock"></el-input>
        </el-form-item>

        <el-form-item label="接口地址">
          <el-input v-model="form.data.intfAddress" placeholder="必填项" :readonly="!currentIntf.isLock" class="desc"></el-input>
          <el-select v-model="form.data.method" class="select-method" disabled>
            <el-option :label="item.name" :value="item.type" v-if="item.status" v-for="item of form.methods" :key="item.type"></el-option>
          </el-select>
        </el-form-item>
        <!-- 入参输入 -->
        <el-form-item label-width="auto" label="入参字符串 (注释请附带在每一行之后)">
        </el-form-item>
        <el-form-item class="params">
          <!-- get方式 -->
          <div v-show="showGetMethod">
            <edit-params @deleteParam="deleteParam" @addParams="addParams" :getFormParams="form.getFormParams" buttonValue="添加query参数"></edit-params>
          </div>
          <!-- post方式 -->
          <div v-show="form.data.method === form.methods[1].type">
            <el-radio-group v-model="form.data.way">
              <el-radio label="form" v-if="!!currentIntf.isLock || form.data.way==='form'"></el-radio>
              <el-radio label="json" v-if="!!currentIntf.isLock || form.data.way==='json'"></el-radio>
            </el-radio-group>
            <!-- form -->
            <div v-show="form.data.way === form.post.form" class="add-params">
              <!-- 参数列表 post-->
              <edit-params @deleteParam="deleteParam" @addParams="addParams" :formParams="form.formParams" :isLock="currentIntf.isLock" buttonValue="添加form参数"></edit-params>
            </div>
            <!-- json -->
            <div v-show="form.data.way === form.post.json" class="json">
              <el-row>
                <el-col :span="11" class="json-content-left">
                  <el-row>
                    <el-col :span="17">
                      <el-form-item label-width="auto" label="接口入参(标准格式的json数据)" />
                    </el-col>
                    <el-col :span="7" v-if="currentIntf.isLock">
                      <el-select v-model="form.inputSelected" placeholder="请到模板管理添加" @change="changeInputTemplate">
                        <el-option v-for="(item, index) in form.templates" :key="item.templateName" :label="item.templateName" :value="index">
                        </el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                  <el-form-item label="" style="position: relative;">
                    <div class="fxh-transform" v-if="currentIntf.isLock">
                      <el-button size="mini" type="primary" @click="changeInParam('input')">转化</el-button>
                    </div>
                    <el-input type="textarea" :readonly="!currentIntf.isLock" v-model="form.data.inParams" class="input-value" :rows="rows" resize="none"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="11">
                  <el-row>
                    <el-col :span="17">
                      <el-form-item label-width="auto" label="接口入参(参数说明)" />
                    </el-col>
                  </el-row>
                  <el-form-item label="">
                    <el-input type="textarea" :readonly="!currentIntf.isLock" v-model="form.data.descInParams" class="input-value" :rows="rows" resize="none"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form-item>

        <el-form-item label-width="auto" label="出参字符串 (注释请附带在每一行之后)" />
        <el-form-item label="">
          <!-- <el-input type="textarea" v-model="form.data.resultOutParams" clearable class="output-value" rows="10" resize="none"></el-input> -->
          <el-row>
            <el-col :span="11" class="json-content-left">
              <el-row>
                <el-col :span="17">
                  <el-form-item label-width="auto" label="接口出参(标准格式的json数据)" />
                </el-col>
                <el-col :span="7" v-if="currentIntf.isLock">
                  <el-select v-model="form.outputSelected" placeholder="请到模板管理添加" @change="changeOutputTemplate">
                    <el-option v-for="(item,index) in form.templates" :key="item.templateName" :label="item.templateName" :value="index">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-form-item label="" style="position: relative;">
                <div class="fxh-transform" v-if="currentIntf.isLock">
                  <el-button size="mini" type="primary" @click="changeInParam">转化</el-button>
                </div>
                <el-input type="textarea" :readonly="!currentIntf.isLock" v-model="form.data.resultOutParams" class="input-value" :rows="rows" resize="none"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-row>
                <el-col :span="17">
                  <el-form-item label-width="auto" label="接口出参(参数说明)" />
                </el-col>
              </el-row>
              <el-form-item label="">
                <el-input type="textarea" :readonly="!currentIntf.isLock" v-model="form.data.descOutParams" class="input-value" :rows="rows" resize="none"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- 接口图文描述 -->
        <el-form-item label-width="auto" label="接口图文描述" />
        <el-form-item label="">
          <el-row>
            <el-col :span="22">
              <div id="father">
                <wang-editor :isLock="currentIntf.isLock" :catchData="catchData" :content="form.data.editorHtml"></wang-editor>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item v-if="currentIntf.isLock">
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="changeShowUpdateItem">添加修改记录</el-button>
        </el-form-item>
      </el-form>

      <!-- 添加修改记录的dialog -->
      <el-dialog title="添加修改记录" :visible.sync="showUpdateItem" class="update-record" center>
        <div slot="title" class="dialog-title">
          <h1>添加修改记录</h1>
        </div>
        <el-form :model="form.record" class="record-form">
          <el-form-item label="标题">
            <el-input v-model="form.record.title" autocomplete="off" class="input-title"></el-input>
          </el-form-item>
          <el-form-item label="内容">
            <el-input v-model="form.record.content" rows="10" type="textarea" autocomplete="off" class="record-content"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="changeShowUpdateItem">取 消</el-button>
          <el-button type="primary" @click="saveRecord">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import EditParams from "./params";
import { mapState } from "vuex"
import { request } from "@/js/_x/utils/request";
import NoData from "../../../common/noData"
import WangEditor from './wangEditor'

let defaultForm = {
  record: {
    title: "",
    content: ""
  },
  methods: [
    { name: "get", type: "get", status: 0 },
    { name: "post", type: "post", status: 1 }
  ],
  post: {
    form: "form",
    json: "json"
  },
  /* 入参模板 */
  templates: [],
  inputSelected: "",
  outputSelected: "",
  /* 提交到后台的参数对象 */
  data: {
    description: "",
    intfAddress: "",
    method: "post",
    /* post提交类型-默认form */
    way: "form",
    inParams: "",
    descInParams: "",
    resultOutParams: "",
    descOutParams: "",
    editorHtml: ""
  },
  /* 接口 */
  getFormParams: [],
  formParams: [],
  /* 提交的修改记录 */
  modifyDesc: ""
}

export default {
  name: "edit",
  props: ["editTimes"],
  components: {
    EditParams,
    NoData,
    WangEditor
  },
  computed: {
    // ...mapState("aside",["currentProject", "currentIntf"]),
    ...mapState({
      currentProject: state => state.aside.currentProject,
      currentIntf: state => state.aside.currentIntf,
      password: state => state.aside.password,
      whetherLock: state => state.aside.whetherLock
    }),
    showGetMethod () {
      return this.form.data.method === this.form.methods[0].type;
    }
  },
  data () {
    return {
      content: "",
      showUpdateItem: false,
      noData: true,
      rows: 20,
      form: JSON.parse(JSON.stringify(defaultForm))
    };
  },
  watch: {
    currentIntf: function () {
      this.getDataShow()
    },
    whetherLock: function () {
      this.$set(this.currentIntf, "isLock", this.currentIntf.isLock === 1 ? 0 : 1)
    },
    editTimes: function () {
      this.getDataShow()
    }
  },
  methods: {
    catchData (value) {
      //在这里接受子组件传过来的参数，赋值给data里的参数
      this.form.data.editorHtml = value
    },
    getDataShow () {
      if (this.currentIntf.isLeaf) {
        this.noData = false
        this.getInftDataById()
      } else {
        this.noData = true
      }
    },
    /* 获取接口数据方法 */
    getInftDataById () {
      /* 数据清空 */

      const params = {
        projectName: this.currentProject,
        id: this.currentIntf.id
      }
      request("api/interface/node/get_interface_data", params, resp => {
        // console.log(resp);
        this.form.data = resp.data
        if (resp.result && resp.data) {
          if (resp.data.method === this.form.methods[0].name) {
            this.form.getFormParams = resp.data.inParams
            this.form.data.inParams = ""
          } else if (resp.data.method === this.form.methods[1].name && resp.data.way === "form") {
            this.form.formParams = resp.data.inParams
            this.form.data.inParams = ""
          }
        } else {
          this.resetData()
        }
      }).catch(error => {
        console.log(error);
        this.resetData()
      }).finally(() => {
        this.getTemplatesData()
      })
    },
    // 获取模板数据列表
    getTemplatesData () {
      let params = {
        projectName: this.currentProject
      }
      this.form.templates = []
      this.form.outputSelected = ""
      this.form.inputSelected = ""
      request("api/interface/template/get_template_view", params, resp => {
        if (resp.result && resp.data && resp.data.length > 0) {
          this.form.templates = resp.data
          this.form.outputSelected = 0
          this.form.inputSelected = 0
          if (!this.form.data) {
            // 设置模板的默认值
            this.form.data.inParams = this.formatJsonData(JSON.parse(this.form.templates[0].templateData))
            this.form.data.resultOutParams = this.formatJsonData(JSON.parse(this.form.templates[0].templateData))
          } else {
            if (!this.form.data.inParams) {
              this.form.data.inParams = this.formatJsonData(JSON.parse(this.form.templates[0].templateData))
            }
            if (!this.form.data.resultOutParams) {
              this.form.data.resultOutParams = this.formatJsonData(JSON.parse(this.form.templates[0].templateData))
            }
          }
        }
      }).catch(error => {
        console.log(error);
      });
    },
    changeOutputTemplate () {
      this.form.data.resultOutParams = this.formatJsonData(JSON.parse(this.form.templates[this.form.outputSelected].templateData))
    },
    changeInputTemplate () {
      this.form.data.inParams = this.formatJsonData(JSON.parse(this.form.templates[this.form.inputSelected].templateData))
    },
    resetData () {
      this.form = JSON.parse(JSON.stringify(defaultForm))
    },
    /* 提交接口数据到后台 */
    onSubmit () {
      /* 数据处理-转化 */
      let data = JSON.parse(JSON.stringify(this.form.data))
      this.changeSubmitData(data)
      let params = {
        projectName: this.currentProject,
        id: this.currentIntf.id,
        password: this.password,
        data: data
      }
      request("api/interface/node/ad_up_interface_data", params, resp => {
        if (resp.result) {
          this.$message({ type: "success", message: "保存成功!" })
        } else {
          this.$message({ type: "error", message: resp.message })
        }
      }).catch(error => {
        console.log(error);
      });
    },
    /* 数据处理-转化 */
    changeSubmitData (data) {
      // 过滤掉名字为空的参数项
      if (data.method === "get") {
        data.inParams = this.form.getFormParams.filter(item => item.name)
      } else if (data.method === "post" && data.way === "form") {
        data.inParams = this.form.formParams.filter(item => item.name)
      }
    },
    /* 控制是否显示修改记录弹框 */
    changeShowUpdateItem () {
      if (!this.showUpdateItem) {
        // 清空之前的数据
        this.form.record.title = ""
        this.form.record.content = ""
      }
      this.showUpdateItem = !this.showUpdateItem;
    },
    /* 保存接口的修改记录数据  */
    saveRecord () {
      /* 验证数据 */
      if (!this.form.record.content) {
        this.$message({ type: "warning", message: "请输入内容项!" })
        return
      }
      // 处理数据
      let data = JSON.parse(JSON.stringify(this.form.data))
      this.changeSubmitData(data)
      this.form.record.createTime = new Date().getTime()
      let params = {
        projectName: this.currentProject,
        id: this.currentIntf.id,
        password: this.password,
        data: data,
        modifyDesc: this.form.record
      }
      request("api/interface/node/update_and_add_record", params, resp => {
        if (resp.result) {
          this.$message({ type: "success", message: "保存修改记录成功!" })
          this.changeShowUpdateItem()
        } else {
          this.$message({ type: "error", message: resp.message })
        }
      }).catch(error => {
        console.log(error);
        this.$message({ type: "error", message: "后台异常,保存失败!" })
      });
    },
    addUpdateItem () { },
    addParams (paramsArr) {
      let obj = {
        name: "",
        type: "text",
        isRequire: false,
        example: "",
        remark: ""
      };
      paramsArr.push(obj);
    },
    deleteParam (paramsArr, index) {
      paramsArr.splice(index, 1);
    },
    /* 格式化入参的方法 */
    changeInParam (type) {
      // type: input/output
      let sourceData = type === "input" ? this.form.data.inParams : this.form.data.resultOutParams
      let targetData = type === "input" ? this.form.data.descInParams : this.form.data.descOutParams
      targetData = targetData || "{}"
      // 验证参数是否是标准json格式
      if (this.validJson(sourceData)) {
        // 第一，生成描述参数
        let result = this.changeInputParamsToData(JSON.parse(sourceData), JSON.parse(targetData), type === "input")
        // 第二在去掉结果中多余的参数
        this.norepeatInputParamsToData(JSON.parse(sourceData), result)
        // 设置值,同时格式化数据
        if (type === "input") {
          this.form.data.inParams = JSON.stringify(JSON.parse(sourceData), null, 2)
          this.form.data.descInParams = JSON.stringify(result, null, 2)
        } else {
          this.form.data.resultOutParams = JSON.stringify(JSON.parse(sourceData), null, 2)
          this.form.data.descOutParams = JSON.stringify(result, null, 2)
        }
      }
    },
    /* 将入参转换成验证类型数据 */
    changeInputParamsToData (data, formatData = {}, flag) {
      if (!data) {
        return;
      }
      const types = ["[object Array]", "[object Object]"]
      const _toString = Object.prototype.toString;
      const objStr = "object"
      const arrStr = "array"
      // 转化
      console.log("dddddd")
      for (let prop in data) {
        let type = typeof data[prop]
        if (type === objStr && data[prop] !== null) {
          if (_toString.call(data[prop]) === types[0]) {
            // 数组
            if (!formatData[prop]) {
              let value = {
                type: arrStr,
                children: {}
              }
              formatData[prop] = value
            }
            this.changeInputParamsToData(data[prop], formatData[prop].children, flag)
          } else if (_toString.call(data[prop]) === types[1]) {
            // 对象
            if (!formatData[prop]) {
              let value = {
                type: objStr,
                children: {}
              }
              formatData[prop] = value
            }
            this.changeInputParamsToData(data[prop], formatData[prop].children, flag)
          }
        } else {
          // 基本数据类型参数生成
          if (!formatData[prop] || _toString.call(data) === types[0]) {
            // 不存在或者是数组的情况下重新生成
            let value
            if (flag) {
              value = {
                type: type,
                require: false,
                desc: "",
                regex: ""
              }
            } else {
              value = {
                type: type,
                desc: ""
              }
            }
            formatData[prop] = value
          }
        }
      }
      return formatData
    },
    // 去掉结果中多余的参数选项
    norepeatInputParamsToData (data, formatData = {}) {
      if (!data) {
        return;
      }
      const types = ["[object Array]", "[object Object]"]
      const _toString = Object.prototype.toString;
      const objStr = "object"
      // 转化

      for (let prop in formatData) {
        if (!data[prop]) {
          delete formatData[prop]
          continue
        }
        let type = formatData[prop].type
        if (type === "object" || type === "array") {
          this.norepeatInputParamsToData(data[prop], formatData[prop].children)
        }
      }
      return formatData
    },
    // 验证是否是标准的json格式数据字符串
    validJson (json) {
      try {
        JSON.parse(json)
        return true
      } catch (error) {
        this.$message({ type: "error", message: "请输入json格式的数据!" })
        return false;
      }
    },
    formatJsonData (data, space = 2) {
      return JSON.stringify(data, null, space)
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/home/content/edit";
</style>
